import {
  Controller,
  Post,
  UploadedFile,
  UploadedFiles,
  UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import { createWriteStream } from 'fs';
import { join } from 'path';
import { env } from 'process';
const { v4: uuidv4 } = require('uuid');
@Controller('upload')
export class UploadController {
  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile() file: Express.Multer.File) {
    console.log(file);
    const uuid = uuidv4(); // 生成一个UUID
    const fileName =
      uuid + file.originalname.substring(file.originalname.lastIndexOf('.'));
    const writeStream = createWriteStream(
      join(__dirname, '../../public', `${fileName}`),
    );
    writeStream.write(file.buffer);
    console.log('测试上传', fileName);
    return {
      code: 200,
      data: env.httpUrl + '/public/' + fileName,
    };
  }
  @Post('uploads')
  @UseInterceptors(FilesInterceptor('files'))
  uploadFiles(@UploadedFiles() files: Array<Express.Multer.File>) {
    files.forEach((item) => {
      createWriteStream(
        join(__dirname, '../../public', `${item.originalname}`),
      ).write(item.buffer);
    });
    return files.map(
      (item) => 'http://localhost:3000/public/' + item.originalname,
    );
  }
}
